package com.google.sketchup;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URL;
import java.net.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

/**
 * Servlet implementation class ModelFetcher
 */
public class ModelFetcher extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ModelFetcher() {
        super();
        
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//super.doGet(request, response);
		        String stext=request.getParameter("searchtext");//get element user has filled in the formular  		        
                PrintWriter out=response.getWriter();

		        String url;
		        Parser parser;
		        NodeFilter filter;
		        NodeList list;
		        if (stext==null||stext.isEmpty()){//default value
		        	stext="car";
		        }
		        
		       url = "http://sketchup.google.com/3dwarehouse/search?q="+stext+"&styp=m";	
		        
		        // find out all the image with imageTag and whose class equal to pict_model under this url	
		        filter = new NodeClassFilter (ImageTag.class);
		        filter = new AndFilter (
		                filter,
		                new NodeFilter ()
		                {
		                    public boolean accept (Node node)
		                    {
		                    //	System.out.println (node.toHtml());
		                        return ("pict_model".equalsIgnoreCase(((ImageTag)node).getAttribute("class")));
		                    }
		                }
		            );
		        out.println("<HTML>\n" +
		        		"<HEAD>\n" +
		        		"<TITLE>Stock List</TITLE>\n" +
		        		"<style>\n"+
		        		".pict_model {border:1px solid #336699; width:100px;height:75px;}\n"+
		        		"</style>\n"+
		        		"<SCRIPT LANGUAGE='JavaScript'>\n" +
		        				"<!--\n" +
		        				"function setModel(model) {\n" +
		        				"  if (window.opener && !window.opener.closed)" +
		        				"    window.opener.document.getElementById('modelid').value = model;\n" +
		        				"    window.opener.document.getElementById('searchtext').value = document.form.searchtext.value;\n" +
		        				"  window.close();\n" +
		        				"}\n" +
		        				"// -->\n" +
		        				"</SCRIPT>\n" +
		        				"</HEAD>\n" +
		        				"<form method='GET' name='form' action=''>Search a model:\n" +
		        				"<input name='searchtext' type='text' size='50' value="+stext +">\n" +
		        				"<input name='submit' type='submit' value='Submit'>\n" +
		        				"</form>\n" );
		        try
		        {
		            parser = new Parser (url);
		            list = parser.extractAllNodesThatMatch (filter);
		            for (int i = 0; i < list.size (); i++){
		            	ImageTag image=(ImageTag)list.elementAt (i);
		            	image.setImageURL(image.getImageURL());
		            	String imageurl=image.getImageURL();
		            	//model id
		            	String query[]=imageurl.split("\\?")[1].split("&");
		            	String model="";
		            	for (int j=0;j<query.length;j++){
		            		String av[]=query[j].split("=");
		            		if("mid".equalsIgnoreCase(av[0])){
		            			model=av[1];
		            		}
		            	}
		                System.out.println (list.elementAt (i).toHtml ());
		                
		                out.println("<a href='' onclick='setModel(\""+model+"\")'>"+list.elementAt (i).toHtml ()+"</a>");
		            }
		        }
		        catch (ParserException e)
		        {
		            e.printStackTrace ();
		        }		    
		    		
		        out.println("<p><input type='button' value='Cancel' onclick='self.close();'></BODY>\n" +
		        		"</HTML>\n");


	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doPost(request, response);
	}

}
